package com.demo.nien;

import com.demo.util.Print;
import org.junit.jupiter.api.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lkz
 * @ClassName: CreateThreadPoolDemo2
 * @description: 线程池钩子函数
 * @date 2022/6/14 14:17
 */
public class CreateThreadPoolDemo2 {


    @Test
    public void testHooks() throws InterruptedException {
        ExecutorService pool = new ThreadPoolExecutor(2, //coreSize

                4, //最大线程数
                60,//空闲保活时长
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(2)) //等待队列
        {
            //继承：调度器终止钩子
            @Override
            protected void terminated()
            {
                Print.tco("调度器已经终止!");
            }
            //继承：执行前钩子
            @Override
            protected void beforeExecute(Thread t, Runnable target)
            {
                Print.tco( target +"前钩被执行");
                //记录开始执行时间

                super.beforeExecute(t, target);
            }
            //继承：执行后钩子
            @Override
            protected void afterExecute(Runnable target, Throwable t)
            {
                super.afterExecute(target, t);
                //计算执行时长
                Print.tco( target +"后钩被执行");

                //清空本地变量
            }
        };
        for (int i = 1; i <= 5; i++)
        {
            pool.execute(()->{
                System.out.println("线程执行------");
            });
        }
        //等待 10 秒
        Thread.sleep(10000);
        Print.tco("关闭线程池");
        pool.shutdown();
    }

}
